<template>
  <div class="list-container">
    <!-- 搜索和操作栏 -->
    <div class="list-header">
      <div class="search-form">
        <!-- 
          注意：后端 GoodCategoryController.list 接口目前只接收 page 和 size 参数
          尚未实现按名称搜索。此处保留搜索框 UI，待后端支持后即可生效。
        -->
        <div class="search-form-item">
          <label>分类名称</label>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
      </div>
      <div class="search-actions">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><RefreshRight /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增分类
        </el-button>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="list-content">
      <div class="list-table" v-loading="loading">
        <div class="table-scroll-wrapper" ref="tableScroll">
          <el-table
            ref="tableRef"
            :data="tableData"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="id" label="ID" width="80" align="center" sortable />
            <el-table-column prop="categoryName" label="分类名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="sort" label="排序" width="100" align="center" sortable />
            <el-table-column prop="quantity" label="商品数量" width="120" align="center" />
            
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>

            <el-table-column prop="addTime" label="添加时间" width="180" align="center" sortable>
              <template #default="{ row }">
                {{ formatDateTime(row.addTime) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="updateTime" label="更新时间" width="180" align="center" sortable>
              <template #default="{ row }">
                {{ formatDateTime(row.updateTime) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button type="primary" size="small" @click="handleEdit(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 水平滑动进度条 -->
        <input
          v-show="showHScroll"
          ref="hSlider"
          class="horizontal-scroll"
          type="range"
          min="0"
          max="100"
          :value="hScrollPercent"
          @input="onSliderInput"
        />
      </div>
    </div>

    <!-- 分页 -->
    <div class="list-footer">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <CategoryDialog
      v-model:visible="dialogVisible"
      :is-edit="isEdit"
      :category-data="currentCategory"
      :loading="submitLoading"
      @success="handleFormSubmit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Plus, Delete } from '@element-plus/icons-vue'
import '@/assets/css/table-list.css'
import CategoryDialog from '@/components/dialogs/CategoryDialog.vue'
import {
  getCategoryList,
  addCategory,
  updateCategory,
  deleteCategory,
  updateCategoryStatus
} from '@/api/goodCategory'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 列表数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const tableRef = ref()

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentCategory = ref(null)

// 滚动条逻辑
const tableScroll = ref(null)
const hScrollPercent = ref(0)
const showHScroll = ref(false)

// 格式化时间
const formatDateTime = (time) => {
  if (!time) return ''
  return time.replace('T', ' ').substring(0, 19)
}

// 获取列表
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      // name: searchForm.name || undefined // 后端暂不支持，预留
    }
    const res = await getCategoryList(params)
    if (res.success) {
      tableData.value = res.data.data || []
      pagination.total = res.data.total || 0
      setTimeout(() => updateHScroll(), 50)
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取分类列表异常')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchList()
}

const handleReset = () => {
  searchForm.name = ''
  pagination.currentPage = 1
  fetchList()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchList()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleStatusChange = async (row) => {
  try {
    const res = await updateCategoryStatus(row.id, row.status)
    if (res.success) {
      ElMessage.success('状态更新成功')
    } else {
      // 失败回滚
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(res.msg || '状态更新失败')
    }
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新异常')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除分类 "${row.categoryName}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteCategory(row.id)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}

const handleAdd = () => {
  isEdit.value = false
  currentCategory.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  // 复制一份数据避免修改表格原数据，直到提交成功
  currentCategory.value = { ...row }
  dialogVisible.value = true
}

const handleFormSubmit = async (formData) => {
  submitLoading.value = true
  try {
    const api = isEdit.value ? updateCategory : addCategory
    const res = await api(formData)
    if (res.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作异常')
  } finally {
    submitLoading.value = false
  }
}

// 滚动条逻辑
const updateHScroll = () => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  if (maxScroll > 0) {
    showHScroll.value = true
    hScrollPercent.value = Math.round((el.scrollLeft / maxScroll) * 100)
  } else {
    showHScroll.value = false
    hScrollPercent.value = 0
  }
}

const onTableScroll = () => {
  updateHScroll()
}

const onSliderInput = (e) => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  const percent = Number(e.target.value || 0)
  el.scrollLeft = Math.round((percent / 100) * maxScroll)
  hScrollPercent.value = percent
}

onMounted(() => {
  fetchList()
  setTimeout(() => {
    if (tableScroll.value) {
      tableScroll.value.addEventListener('scroll', onTableScroll, { passive: true })
      updateHScroll()
    }
  }, 100)
  window.addEventListener('resize', updateHScroll)
})

onBeforeUnmount(() => {
  if (tableScroll.value) {
    tableScroll.value.removeEventListener('scroll', onTableScroll)
  }
  window.removeEventListener('resize', updateHScroll)
})
</script>
